package com.sale.succ.forms;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import com.sale.succ.components.DefForm;
import com.sale.succ.components.DefScrollBarPanel;
import com.sale.succ.components.MessDialog;
import com.sale.succ.components.orders.OrdersTable;
import com.sale.succ.components.orders.OrdersTableModel;
import com.sale.succ.datacomp.produce.ProduceListener;
import com.sale.succ.objects.OrderObj;
import com.sale.succ.objects.ProductObj;
import com.sale.succ.objects.Session;
import com.sale.succ.system.txt.ObjectsProvider;
import com.sale.succ.system.txt.TXTProcessing;
import com.sale.succ.utils.SystemConstants;
import com.sale.succ.utils.TraderConstants;
import com.sale.succ.utils.TraderHelper;

import eve.fx.Insets;
import eve.fx.gui.WindowConstants;
import eve.sys.Event;
import eve.sys.EventListener;
import eve.ui.CellPanel;
import eve.ui.Gui;
import eve.ui.Label;
import eve.ui.event.ControlEvent;

public class OrdersForm extends DefForm implements ProduceListener {
	private CellPanel mainPanel;
	private OrdersTable ordersTable;
	private CellPanel detailPanel;

	public OrdersTable getOrdersTable() {
		if (ordersTable == null) {
			ordersTable = new OrdersTable(this);
		}
		return ordersTable;
	}

	private Label tradeNameLabel;
	private Label sumLabel;

	private CellPanel getDetailPanel() {
		if (detailPanel == null) {
			Label tradeTitleLabel = new Label(TraderHelper.getLabel(TraderConstants.TRADE_NAME) + ":");
			Label sumOrderTitleLabel = new Label(TraderHelper.getLabel(TraderConstants.SUMM_ORDER) + ":");

			tradeNameLabel = new Label("");
			tradeNameLabel.setPreferredSize(Gui.DESKTOP_WIDTH, 20);
			sumLabel = new Label("");
			sumLabel.setPreferredSize(Gui.DESKTOP_WIDTH, 20);

			detailPanel = new CellPanel();
			detailPanel.defaultTags.set(TAG_INSETS, new Insets(0, 0, 0, 0));

			detailPanel.addNext(tradeTitleLabel).setCell(HSHRINK);
			detailPanel.addLast(tradeNameLabel);
			detailPanel.addNext(sumOrderTitleLabel).setCell(HSHRINK);
			detailPanel.addLast(sumLabel);
		}
		return detailPanel;
	}

	public OrdersForm() {
		title = TraderHelper.getLabel(TraderConstants.ORDERS_TITLE);
		addLast(getMainPanel());
		windowFlagsToSet |= WindowConstants.FLAG_MAXIMIZE;
		initData();
		doButtons(OKB | CANCELB);
		ok.addListener(new EventListener() {
			public void onEvent(Event ev) {
				if (ev.type == ControlEvent.PRESSED) {
					saveOrders();
				}
			}

		});
		cancel.addListener(new EventListener() {
			public void onEvent(Event ev) {
				if (ev.type == ControlEvent.PRESSED) {
					success = true;
				}
			}

		});
	}

	private boolean success = true;

	private void saveOrders() {
		ArrayList orders = ((OrdersTableModel) getOrdersTable().getTableModel()).getOrders();
		ArrayList ordersToSave = new ArrayList();

		for (int i = 0; i < orders.size(); i++) {
			OrderObj orderObj = (OrderObj) orders.get(i);
			if (orderObj.getOrder().equals("0")) {
				continue;
			}
			ArrayList orderToAdd = new ArrayList();
			orderToAdd.add(orderObj.getClientId());
			orderToAdd.add(orderObj.getTradeId());
			orderToAdd.add(orderObj.getProductId());
			orderToAdd.add(orderObj.getPrice());
			orderToAdd.add(orderObj.getOrder());
			orderToAdd.add(orderObj.getFwId());
			orderToAdd.add(orderObj.getDateGive());
			orderToAdd.add(orderObj.getCertificates());
			orderToAdd.add(orderObj.getPayDate());
			orderToAdd.add(orderObj.getMoneyCondition());
			orderToAdd.add(orderObj.getTablet());
			orderToAdd.add(orderObj.getExchange());
			orderToAdd.add(orderObj.getNotes());
			orderToAdd.add(orderObj.getAsFact());
			ordersToSave.add(orderToAdd);
		}

		success = ObjectsProvider.getInstance().saveOrderObjectCollection(
				Session.getInstance().getClientId(),
				ordersToSave, false
				);
		if (success) {
			modifyRests();
			new MessDialog(TraderHelper.getLabel(TraderConstants.ORDERS_SAVED)).execute();
		}
	}

	private void modifyRests() {
		HashMap rests = ((OrdersTableModel) getOrdersTable().getTableModel())
				.getRests();
		Set keys = rests.keySet();
		Iterator it = keys.iterator();
		while (it.hasNext()) {
			String prodId = (String) it.next();
			ProductObj product = (ProductObj) ObjectsProvider.getInstance()
					.getProductCollection().get(prodId);
			product.setGlobalRest(product.getGlobalRest()
					+ Integer.parseInt(rests.get(prodId).toString()));
		}
		//save rests to file
		ArrayList tempRest = new ArrayList();
		keys = ObjectsProvider.getInstance().getProductCollection().keySet();
		it = keys.iterator();
		while (it.hasNext()) {
			String prodId = (String) it.next();
			ProductObj product = (ProductObj) ObjectsProvider.getInstance().getProductCollection().get(prodId);
			if(product.getGlobalRest() != 0){
				ArrayList temp = new ArrayList();
				temp.add(prodId);
				temp.add(product.getGlobalRest() + "");
				tempRest.add(temp);
			}
		}
		
		String fileName = SystemConstants.TRADE_ZIP_DIR + File.separator + SystemConstants.RESTS_FILE;
		TXTProcessing.getTXTFromCollection(tempRest, fileName, false);
		
	}

	protected boolean canExit(int exitCode) {
		if (success)
			return true;
		return false;
	}

	private void initData() {
		ArrayList list = new ArrayList();
		list.add(getOrdersTable().getOrdersModel().getSum() + "");
		applyProduceDetails(list, true);
	}

	private CellPanel getMainPanel() {
		if (mainPanel == null) {
			mainPanel = new CellPanel();
			DefScrollBarPanel scrollPanel = new DefScrollBarPanel(getOrdersTable());
			mainPanel.addLast(scrollPanel);
			mainPanel.addLast(getDetailPanel()).setCell(VSHRINK);
		}
		return mainPanel;
	}

	/**
	 * 0 - trade name
	 */
	public void applyProduceDetails(ArrayList list, boolean updateSome) {
		if (updateSome) {
			sumLabel.setText(list.get(list.size() - 1).toString());
			return;
		}
		tradeNameLabel.setText(list.get(0).toString());
	}

}
